<template>
  <Button :type="buttonType" :disabled="!canSendEmailCode" @click="submit">{{sendEmailCodeButtonText}}</Button>
</template>

<script>
export default {
  name: 'SendEmailCodeButton',
  props: {
    buttonText: {
      type: String,
      default: '发送验证码'
    },
    timeInterval: {
      type: Number,
      default: 90
    },
    sendEmailCodeMethod: {
      type: Function,
      required: true
    },
    buttonType: {
      type: String,
      default: 'primary'
    }
  },
  data () {
    return {
      nextEmailCodeTime: 0
    }
  },

  computed: {
    canSendEmailCode () {
      return this.nextEmailCodeTime <= 0
    },
    sendEmailCodeButtonText () {
      if (this.nextEmailCodeTime === 0) {
        return this.buttonText
      } else {
        return `${this.nextEmailCodeTime}s后重新发送`
      }
    }
  },

  methods: {
    submit () {
      if (this.sendEmailCodeMethod()) {
        this.nextEmailCodeTime = 90
        const interval = setInterval(() => {
          this.nextEmailCodeTime = this.nextEmailCodeTime - 1
          if (this.nextEmailCodeTime <= 0) {
            window.clearInterval(interval)
          }
        }, 1000)
      }
    }
  }
}
</script>

<style scoped>

</style>
